// pages/newaddress/newaddress.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    name: "",
    number: "",
    address: "",
    edit: false,
  },
  setMsg(options) {
    let type = options.target.dataset.type;
    let value = options.detail.value;
    if (value) {
      if (type == 1) {
        this.setData({
          name: value
        })
      } else if (type == 2) {
        this.setData({
          number: value
        })
      } else if (type == 3) {
        this.setData({
          address: value
        })
      }
    }
  },
  // 新增完成
  addDone() {
    if (this.data.name && this.data.number && this.data.address) {
      let msg = {
        name: this.data.name,
        number: this.data.number,
        address: this.data.address,
        default: false,
      }
      wx.setStorageSync('newAddress', msg);
      wx.navigateBack()
    } 
    // else {
    //   wx.showToast({
    //     title: '请输入完整的信息',
    //     icon: 'none'
    //   })
    // }
  },
  // 完成修改修改
  editDone() {
    let data = wx.getStorageSync('address');
    let index = wx.getStorageSync('editIndex') - 1;
    data[index].name = this.data.name;
    data[index].number = this.data.number;
    data[index].address = this.data.address;
    wx.setStorageSync('address', data);
    wx.navigateBack();
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (wx.getStorageSync('editIndex')) {
      let index = wx.getStorageSync('editIndex') - 1;
      let data = wx.getStorageSync('address')
      this.setData({
        edit: true,
        name: data[index].name,
        number: data[index].number,
        address: data[index].address,
      })
    } else {
      this.setData({
        edit: false,
        name: "",
        number: "",
        address: "",
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    let newAddress = wx.getStorageSync('newAddress');
    if (newAddress) {
      let address = wx.getStorageSync('address');
      address.push(newAddress);
      // console.log("添加了旧地址之后的新地址====》", address);
      wx.setStorageSync('address', address);
      wx.removeStorageSync('newAddress')
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})